package com.pay.controller.open.api;

import cn.hutool.extra.spring.SpringUtil;
import com.pay.common.core.api.base.BaseApiController;
import com.pay.common.core.api.base.BaseResponse;
import com.pay.entity.PaymentChannelDO;
import com.pay.service.open.api.PaymentChannelService;
import com.pay.template.AbstractPayCallbackTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author 周益和
 * @ClassName PayCallbackCoreController
 * @qq 1552951165
 */
@RestController
@RequestMapping("/callback")
public class PayCallbackCoreController extends BaseApiController {
    
    @Autowired
    private PaymentChannelService paymentChannelService;
    
    /**
     * 1.同步回调 -----以浏览器的形式 回调通知  解析报文参数
     * 2.异步回调 -------第三方支付系统单独发送rest请求通知
     */
    @PostMapping("/synchCallback")
    public String synchCallback() {
        return "ok";
    }
    
    /**
     * 异步回调
     * @param channelId
     * @return
     */
    @RequestMapping("/asynchCallback/{channelId}")
    public BaseResponse<String> asynchCallback(@PathVariable String channelId) {
        if (StringUtils.isEmpty(channelId)) {
            return setResultError("channelId is error");
        }
        // 根据渠道id查询到对应的渠道信息
        PaymentChannelDO channelIdInfo = paymentChannelService.getByChannelIdInfo(channelId);
        if (channelIdInfo == null) {
            return setResultError("渠道关闭或者错误");
        }
        // 获取回调的beanid
        String callbackBeanId = channelIdInfo.getCallbackBeanId();
        // 从springioc容器中获取该bean对象
        AbstractPayCallbackTemplate payCallbackTemplate = SpringUtil.getBean(callbackBeanId,
                AbstractPayCallbackTemplate.class);
        // 配置 阿里pay相关异步回调：
        // http://www.mayikt.com/asynchCallback?channelId=alipay
        // http://www.mayikt.com/asynchCallback?channelId=yinlian
        return setResultSuccessData(payCallbackTemplate.sasynCallback());
    }
}
